#!/usr/bin/env python
# coding=utf-8
# __author__ = 'Yunchao Ling'

from pymongo import MongoClient
from bson.son import SON
import time
import sys

SERVER = '10.188.188.101'
PORT = 27017
DB_NAME = "pmc"
COLLECTION_NAME = "mesh"

pmid = int(sys.argv[1])
time1 = time.time()
connection = MongoClient(SERVER, PORT)
db = connection[DB_NAME]
collection = db[COLLECTION_NAME]
time2 = time.time()
results = collection.find({"pmid": pmid})
time3 = time.time()
dess = []
for item in results:
    dess.append(item["mesh"]["descriptor"])
print dess
pipeline = [{"$match": {"mesh.descriptor": {"$in": dess}}}, {"$group": {"_id": 1, "count": {"$sum": 1}}},
            {"$sort": SON([("count", -1), ("_id", -1)])}, {"$limit": 10}]
results2 = db.command("aggregate", COLLECTION_NAME, pipeline=pipeline)
time4 = time.time()
print results2
print str(time2 - time1)
print str(time3 - time2)
print str(time4 - time3)

connection.close()
